package com.estore.service;

import com.estore.model.Product;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class ProductService {

    private Map<String, Product> productData = new HashMap<>();
    private String dataFilePath;
    private Properties config;

    // 配置常量
    private static final String CONFIG_FILE = "config.properties";
    private static final String DEFAULT_DATA_FILE = "products.dat";

    public ProductService() {
        loadConfig(); // 加载配置
        loadData();   // 加载数据
    }

    /**
     * 加载配置文件
     */
    private void loadConfig() {
        config = new Properties();
        File configFile = new File(CONFIG_FILE);

        // 如果配置文件不存在，创建默认配置
        if (!configFile.exists()) {
            createDefaultConfig();
            System.out.println("配置文件不存在，已创建默认配置");
        }

        try (FileInputStream fis = new FileInputStream(CONFIG_FILE);
             InputStreamReader isr = new InputStreamReader(fis, "UTF-8")) {

            config.load(isr);
            dataFilePath = config.getProperty("data.file.path", DEFAULT_DATA_FILE);

            System.out.println("=== 配置信息 ===");
            System.out.println("数据文件路径: " + dataFilePath);
            System.out.println("最大备份文件数: " + config.getProperty("max.backup.files", "5"));
            System.out.println("自动保存: " + config.getProperty("auto.save.enabled", "true"));

        } catch (IOException e) {
            System.err.println("加载配置文件失败: " + e.getMessage());
            System.out.println("使用默认配置");
            dataFilePath = DEFAULT_DATA_FILE;
        }
    }

    /**
     * 创建默认配置文件
     */
    private void createDefaultConfig() {
        try (FileOutputStream fos = new FileOutputStream(CONFIG_FILE);
             OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8")) {

            Properties defaultProps = new Properties();
            // 设置默认配置
            defaultProps.setProperty("data.file.path", "products.dat");
            defaultProps.setProperty("backup.file.suffix", ".bak");
            defaultProps.setProperty("max.backup.files", "5");
            defaultProps.setProperty("default.currency", "¥");
            defaultProps.setProperty("max.products.per.page", "10");
            defaultProps.setProperty("auto.save.enabled", "true");
            defaultProps.setProperty("max.cart.items", "50");
            defaultProps.setProperty("allow.negative.stock", "false");
            defaultProps.setProperty("date.format", "yyyy-MM-dd");
            defaultProps.setProperty("time.format", "HH:mm:ss");

            defaultProps.store(osw, "电商系统配置文件");
            System.out.println("默认配置文件创建成功");

        } catch (IOException e) {
            System.err.println("创建默认配置文件失败: " + e.getMessage());
        }
    }

    /**
     * 获取配置值
     */
    public String getConfig(String key, String defaultValue) {
        return config.getProperty(key, defaultValue);
    }

    /**
     * 获取整数配置值
     */
    public int getIntConfig(String key, int defaultValue) {
        try {
            return Integer.parseInt(config.getProperty(key, String.valueOf(defaultValue)));
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    /**
     * 获取布尔配置值
     */
    public boolean getBooleanConfig(String key, boolean defaultValue) {
        String value = config.getProperty(key);
        if (value != null) {
            return Boolean.parseBoolean(value);
        }
        return defaultValue;
    }

    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFilePath))) {
            oos.writeObject(productData);
            boolean autoSave = getBooleanConfig("auto.save.enabled", true);
            if (autoSave) {
                System.out.println("商品数据已自动保存到: " + dataFilePath);
            }
        } catch (IOException e) {
            System.err.println("保存数据失败: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    public void loadData() {
        File file = new File(dataFilePath);
        if (!file.exists()) {
            System.out.println("数据文件不存在，使用默认数据初始化");
            initializeDefaultData();
            return;
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dataFilePath))) {
            Object obj = ois.readObject();
            if (obj instanceof Map) {
                productData = (Map<String, Product>) obj;
                System.out.println("商品数据加载成功，共加载 " + productData.size() + " 个商品");
            }
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("加载数据失败: " + e.getMessage());
            System.out.println("使用默认数据初始化");
            initializeDefaultData();
        }
    }

    /**
     * 增强的备份方法，使用配置参数
     */
    public void backupData() {
        String backupSuffix = config.getProperty("backup.file.suffix", ".bak");
        String backupFile = dataFilePath + backupSuffix;

        try (FileInputStream fis = new FileInputStream(dataFilePath);
             FileOutputStream fos = new FileOutputStream(backupFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            int totalBytes = 0;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
                totalBytes += bytesRead;
            }

            System.out.printf("数据备份成功！备份文件: %s (大小: %.2f KB)\n",
                    backupFile, totalBytes / 1024.0);

            // 清理旧的备份文件（如果配置了最大备份数）
            cleanupOldBackups();

        } catch (IOException e) {
            System.err.println("备份失败: " + e.getMessage());
        }
    }

    /**
     * 清理旧的备份文件
     */
    private void cleanupOldBackups() {
        int maxBackups = getIntConfig("max.backup.files", 5);
        if (maxBackups <= 0) return;

        String backupSuffix = config.getProperty("backup.file.suffix", ".bak");
        File dataDir = new File(".");
        File[] backupFiles = dataDir.listFiles((dir, name) ->
                name.startsWith("products") && name.endsWith(backupSuffix));

        if (backupFiles != null && backupFiles.length > maxBackups) {
            // 按修改时间排序，删除最旧的
            java.util.Arrays.sort(backupFiles, (f1, f2) ->
                    Long.compare(f1.lastModified(), f2.lastModified()));

            for (int i = 0; i < backupFiles.length - maxBackups; i++) {
                if (backupFiles[i].delete()) {
                    System.out.println("删除旧备份文件: " + backupFiles[i].getName());
                }
            }
        }
    }

    private void initializeDefaultData() {
        productData.put("p001", new Product("p001", "Java从入门到精通", 99.0, 100));
        productData.put("p002", new Product("p002", "高性能MySQL", 128.5, 50));
        productData.put("p003", new Product("p003", "颈椎康复指南", 45.0, 200));
        productData.put("p004", new Product("p004", "生发秘籍", 88.0, 0));
    }

    public List<Product> getAllProducts() {
        return new ArrayList<>(productData.values());
    }

    public Product findProductById(String id) {
        return productData.get(id);
    }

    public boolean updateStock(String productId, int quantity) {
        boolean allowNegative = getBooleanConfig("allow.negative.stock", false);
        Product product = productData.get(productId);
        if (product == null) return false;

        if (!allowNegative && product.getStock() < quantity) {
            return false;
        }

        product.setStock(product.getStock() - quantity);
        return true;
    }

    public int getProductCount() {
        return productData.size();
    }
}